package com.summer.common;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.summer.bean.MessagerEntity;
import com.summer.utils.HttpClientUtil;

public class MessagerQueue {
	
	private final BlockingQueue<MessagerEntity> workerQueue = new ArrayBlockingQueue<MessagerEntity>(50);
//	private HttpClientUtil httpClientUtil = new HttpClientUtil();
	private int threadCount = 1000;
	
	private static MessagerQueue mMessagerQueue = null;

	public static MessagerQueue build(){
		if(mMessagerQueue == null)
			mMessagerQueue = new MessagerQueue();
		return mMessagerQueue;
	}
	
	private MessagerQueue(){
		for(int index=0;index<threadCount;index++){
			new SendTaskThread().start();
		}
	}
	
	public void send(MessagerEntity task){
		try{
			workerQueue.put(task);
		}catch(InterruptedException ex){
			Thread.currentThread().interrupt();
		}
	}
	
	private class SendTaskThread extends Thread{
		@Override
		public void run() {
			HttpClientUtil httpClientUtil = new HttpClientUtil();
			while(true){
				MessagerEntity msg = null;
				try {
					
					msg = workerQueue.take();
					String rs = httpClientUtil.sendPost(msg.url, msg.params);

					if(msg.callback != null){
						if(rs!=null && rs.contains("ok"))
							msg.callback.successNotify();
						else
							msg.callback.failNotify();
					}
					
				} catch (Exception e) {
					if(msg!=null && msg.callback != null)
						msg.callback.failNotify();
					
					System.out.println(e.toString());
					
					if(e instanceof InterruptedException)
					;//TODO:队列异常待处理
				}
			}
		}
	}
	
}
